import axios from "axios";
import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import { Flex, Button, Popup, Cell } from "react-vant";
import { ListItem } from "../../components";
import { OrderDetail } from "../../store/user/userReducer";

const Index: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const location = useLocation();
  const v = location.state as OrderDetail;
  const [str, setStr] = useState("00:00:00");
  useEffect(() => {
    const timer = setInterval(() => {
      const time =
        1000 * 60 * 60 * 2 - (new Date().getTime() - v.createDateTime);
      const s = Math.floor((time / 1000) % 60)
        .toString()
        .padStart(2, "0");
      const m = Math.floor((time / 1000 / 60) % 60)
        .toString()
        .padStart(2, "0");
      const h = Math.floor((time / 1000 / 60 / 60) % 24)
        .toString()
        .padStart(2, "0");
      setStr(`${h}:${m}:${s}`);
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, []);

  const payment = async () => {
    // 调用支付宝
    const resp = await axios.post("/api/pay", {
      id: v.id,
      price: v.price,
      title: v.title,
    });
    window.location.href = resp.data.data;
  };

  return (
    <div>
      <Flex>
        <Flex.Item>订单编号:</Flex.Item>
        <Flex.Item>{v.id}</Flex.Item>
      </Flex>
      <Flex>
        <Flex.Item>订单金额:</Flex.Item>
        <Flex.Item>{v.price}</Flex.Item>
      </Flex>
      <Flex>
        <Flex.Item>订单标题:</Flex.Item>
        <Flex.Item>{v.title}</Flex.Item>
      </Flex>
      <div className="card-item">
        <div className="card-content">
          <div className="list">
            {v.projects.map((v) => {
              return (
                <div key={v.id} style={{ padding: 10 }}>
                  <ListItem {...v}></ListItem>
                </div>
              );
            })}
          </div>
        </div>
      </div>
      {v.state === "待付款" && (
        <div>
          <h3 style={{ color: "red", textAlign: "center" }}>
            距离订单失效还剩{str}
          </h3>
          <Button type="primary" square block onClick={() => setVisible(true)}>
            立即支付
          </Button>
        </div>
      )}

      {v.state === "待收货" && <div>物流信息</div>}

      <Popup
        visible={visible}
        onClose={() => setVisible(false)}
        position="bottom"
      >
        <div style={{ padding: "10px" }}>
          <Cell.Group>
            <Cell title="支付宝" onClick={() => payment()} />
            <Cell title="微信" />
          </Cell.Group>
        </div>
      </Popup>
    </div>
  );
};

export default Index;
